﻿@inject IHttpService _httpService


@inject NavigationManager NavigationManager
@inject IJSRuntime JS
@inject IDataCacheService _dataCatcheService
@inject IStructuredDataService _structuredDataService
@inject IPopupService PopupService
@implements IDisposable

@if (string.IsNullOrWhiteSpace(Model.DisplayName) == false)
{
    <CnGalWebSite.Shared.MasaComponent.Shared.Cards.TitleTip Title="@(Model.DisplayName)" Description="@Model.BriefIntroduction" Image="@Model.MainPicture" />
}
else
{
    <CnGalWebSite.Shared.MasaComponent.Shared.Cards.TitleTip />
}
@if (_dataCatcheService.ThemeSetting.IsTransparent)
{
    @if (string.IsNullOrWhiteSpace(Model.SmallBackgroundPicture) == false)
    {
        <div id="web_bg" style="background-image: url(@Model.SmallBackgroundPicture)" class=" d-none  bg-d-lg-block bgimage-ison"></div>
    }
    @if (string.IsNullOrWhiteSpace(Model.BackgroundPicture) == false)
    {
        <div id="web_bg" style="background-image: url(@Model.BackgroundPicture)" class=" d-none d-sm-block bgimage-ison"></div>
    }

}

@if (isNotFound == true)
{
    <NotFoundCard>
        <h1 class="text-center title-large">找不到这篇文章哦......</h1>
        <div class="text-center">可以在这里<a href="/articles/createarticle">发布文章</a>，也可以查看<a href="/articles/index/3">《文章发表规范》</a></div>
    </NotFoundCard>
}
else
{
    <div class="article-page-card">
        <div>
            @if (_dataCatcheService.ArticleIndexPageCatche.Check(Id) || isReady)
            {
                @if (Model.IsHidden == true)
                {
                    <CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaAlert Type="AlertTypes.Warning" Class="mb-3">
                        当前文章处于隐藏状态，如果你看到了这个提示，请立即联系管理员
                    </CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaAlert>
                }

                <CnGalWebSite.Shared.MasaComponent.PC.Articles.MainInforCard Model="Model" OnRevoke="OnRevoke" />

                <div class="ps-4 pe-4 pt-4">
                    <CnGalWebSite.Shared.Component.Articles.NewVersion.OperationCard Model="Model" Class="mb-4" />
                </div>
                <CnGalWebSite.Shared.Component.Articles.NewVersion.RelevancesCard Model="Model" OnRevoke="OnRevoke" />
                <CnGalWebSite.Shared.MasaComponent.PC.FavoriteFolders.CatalogsCard Type="FavoriteObjectType.Article" Id="Model.Id" />

                <CnGalWebSite.Shared.MasaComponent.PC.Comments.CommentTip CanComment="Model.CanComment" CanDeleted="CanDeleted" ObjectId="@Model.Id.ToString()" Type="CommentType.CommentArticle" />

            }
            else
            {
                <CnGalWebSite.Components.Progressings.ProgressingCard Page />

            }
        </div>
    </div>

}
<CnGalWebSite.Shared.MasaComponent.Shared.Components.TrackEvent DataType="TrackEventDataType.Article" EventType="TrackEventType.View" ObjectId="@Model.Id.ToString()"
                                                                ObjectName="@Model.Name" />
@if (isFirstLoad == false)
{
    <CnGalWebSite.Shared.MasaComponent.Shared.Cards.NavLoadingCard IsLoading="isLoading" />
}

@code {
    [Parameter]
    public string Id { get; set; }

    public string CurrentUserRank { get; set; }
    bool isReady = false;
    bool isNotFound = false;
    bool isAsyncReady = false;

    public ArticleViewModel Model { get; set; } = new ArticleViewModel();

    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    string LastLookName = "";
    bool isFrist = true;
    bool CanDeleted;
    bool isLoading = false;
    bool isFirstLoad = true;

    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }
    [CascadingParameter]
    private CnGalWebSite.Shared.Components.CnGalRootTip CnGalRootTip { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (firstRender)
        {
            NavigationManager.LocationChanged -= LocationChanged;
            NavigationManager.LocationChanged += LocationChanged;
            isFirstLoad = false;
        }
    }

    protected override async Task OnInitializedAsync()
    {
        await Refresh();
    }

    protected async Task Refresh()
    {
        try
        {
            //获取文章信息
            Model = await _dataCatcheService.ArticleIndexPageCatche.GetCache(Id);
            //判断文章名称是否为空 为空则跳转到主页
            if (string.IsNullOrWhiteSpace(Model.Name))
            {
                NavigationManager.NavigateTo("/articles/home");
            }


            //展示目录
            CnGalRootTip?.KanbanCard?.DisplayArticleCatalogButton(Model);

            var userState = await authenticationStateTask;
            var user = userState.User;
            if (user.Identity.Name == Model.UserInfor.Name)
            {
                Model.Authority = true;
                CanDeleted = true;
            }
            if (user.IsInRole("Editor"))
            {
                Model.Authority = true;
            }

            //生成轮播结构数据
            await GenerateCarouselStructuredDataJson();

            isReady = true;
            //StateHasChanged();
        }
        catch (Exception exc)
        {
            isReady = true;
            isNotFound = true;
            StateHasChanged();
        }

    }


    public async Task GenerateCarouselStructuredDataJson()
    {
        var urls = new List<string>();

        if (Model.RelatedEntries.Any())
        {
            urls.AddRange(Model.RelatedEntries.Select(s => NavigationManager.BaseUri + "entries/" + s.Id));
        }

        if (Model.RelatedArticles.Any())
        {
            urls.AddRange(Model.RelatedEntries.Select(s => NavigationManager.BaseUri + "articles/" + s.Id));
        }

        await _structuredDataService.SetStructuredData(urls);
    }


    private async Task OnRevoke(Operation operation)
    {
        var ret = await PopupService.ConfirmAsync("确认撤销编辑", "撤销编辑后会删除数据，无法恢复，请谨慎操作");
        if (ret == false)
        {
            return;
        }
        //上传
        try
        {
            var obj = await _httpService.PostAsync<RevokeExamineModel, Result>("api/articles/RevokeExamine", new RevokeExamineModel { Id = Model.Id });
            //判断结果
            if (obj.Successful == false)
            {
                await PopupService.ToastErrorAsync("撤销审核请求失败", obj.Error);
            }
            else
            {
                await PopupService.ToastSuccessAsync("撤销审核请求成功", "撤销审核请求成功");
                //修改各部分编辑状态
                switch (operation)
                {
                    case Operation.EditArticleMain:
                        Model.MainState = EditState.Normal;
                        break;
                    case Operation.EditArticleMainPage:
                        Model.MainPageState = EditState.Normal;
                        break;
                    case Operation.EditArticleRelevanes:
                        Model.RelevancesState = EditState.Normal;
                        break;
                }

                await Refresh();
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "撤销审核请求失败");
        }
    }

    public async void LocationChanged(object sender, LocationChangedEventArgs args)
    {
        if (Id != Model.Id.ToString())
        {
            if (_dataCatcheService.VideoIndexPageCatche.Check(Id) == false)
            {
                isLoading = true;
                StateHasChanged();
                await Refresh();
                isLoading = false;
                StateHasChanged();
            }
            else
            {
                await Refresh();
                StateHasChanged();
            }

        }
    }

    #region 释放实例

    public void Dispose()
    {

        NavigationManager.LocationChanged -= LocationChanged;

        GC.SuppressFinalize(this);
    }
    #endregion
}
